def tokenize(expression):
    # 移除空格并分割字符串
    tokens = expression.split()
    return tokens

def parse(tokens):
    # 解析表达式并构建AST
    def parse_term():
        # 解析项（数字或括号内的表达式）
        factor = parse_factor()
        while tokens and tokens[0] in ('*', '/'):
            op = tokens.pop(0)
            factor = {'op': op, 'left': factor, 'right': parse_factor()}
        return factor

    def parse_factor():
        # 解析因子（数字或括号内的表达式）
        if tokens[0].isdigit():
            return int(tokens.pop(0))
        elif tokens[0] == '(':
            tokens.pop(0)  # 移除左括号
            result = parse_expression()
            tokens.pop(0)  # 移除右括号
            return result
        else:
            raise ValueError('Unexpected token')

    def parse_expression():
        # 解析表达式
        result = parse_term()
        while tokens and tokens[0] in ('+', '-'):
            op = tokens.pop(0)
            result = {'op': op, 'left': result, 'right': parse_term()}
        return result

    return parse_expression()

def evaluate(ast):
    # 计算AST的值
    if isinstance(ast, int):
        return ast
    else:
        left = evaluate(ast['left'])
        right = evaluate(ast['right'])
        if ast['op'] == '+':
            return left + right
        elif ast['op'] == '-':
            return left - right
        elif ast['op'] == '*':
            return left * right
        elif ast['op'] == '/':
            return left / right

expression = "3 * 4 + 2 / 6 - 1"
tokens = tokenize(expression)
ast = parse(tokens)
result = evaluate(ast)
print(result)